package com.jihox.abookpro.helper;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Vector;

import android.graphics.BitmapFactory;

import com.jihox.abookpro.dao.BookTemplateDAO;
import com.jihox.abookpro.domain.Book;
import com.jihox.abookpro.domain.BookProduct;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.BookTemplate;
import com.jihox.abookpro.domain.ImageInfo;
import com.jihox.abookpro.domain.Page;
import com.jihox.abookpro.domain.PagePicture;
import com.jihox.abookpro.domain.PictureHolder;
import com.jihox.abookpro.util.PictureUtil;

public class BookHelper {

	public BookProject makeNewBookProject2(BookProduct product,Vector<File> images,InputStream is,String cacheDir) throws Exception {
		BookProject project = null;
		BookTemplateDAO dao = new BookTemplateDAO();
		BookTemplate template = dao.retrieveBookTemplate(is);

		if (template != null) {
			project = generateProject(product,template,images,cacheDir);
			
		}
		return project;
	}
	
	public BookProject makeNewBookProject(BookProduct product,InputStream is) throws Exception {
		BookProject project = null;
		BookTemplateDAO dao = new BookTemplateDAO();
		BookTemplate template = dao.retrieveBookTemplate(is);

		if (template != null) {
			project = new BookProject();
			Book book = new Book();
			book.setProduct(product);
			book.setPages(template.getPages());
			book.setSpine(template.getSpine());
			project.setBook(book);
		}
		return project;
	}
	
	public BookProject generateProject(BookProduct product,BookTemplate template,
			Vector<File> images,String cacheDir) {
		BookProject project = new BookProject();
		Book book = new Book();
		book.setTemplateName(template.getTemplateName());
//		final BitmapFactory.Options coverImageOptions = new BitmapFactory.Options();
//		coverImageOptions.inJustDecodeBounds = true;
//		BitmapFactory.decodeFile(images.elementAt(0).toString(), coverImageOptions);
		
		//int degree = PictureUtil.readPictureDegree(images.elementAt(0).getPath());
		//float imageHeight =0;
		//float imageWidth = 0;
//		if (degree == 90 || degree == 270) {
//			imageHeight = coverImageOptions.outWidth;
//			imageWidth = coverImageOptions.outHeight;
//		}else{
//			imageHeight = coverImageOptions.outHeight;
//			imageWidth = coverImageOptions.outWidth;
//		}
		
//		float imageRatio = (float)((float)imageHeight/(float)imageWidth);
//		
//		int pageType = Page.UNDEFINED_FRONT_COVER;
//		if (imageRatio > 1){
//			pageType = Page.PORTRAIT_FRONT_COVER;
//		}else if (imageRatio < 1){
//			pageType = Page.LANDSCAPE_FRONT_COVER;
//		}else{
//			pageType = Page.SQUARE_FRONT_COVER;
//		}
		
		// Decode bitmap with inSampleSize set
//		coverImageOptions.inJustDecodeBounds = false;
	
		Vector<Page> pages = new Vector<Page>();
//		Page coverPage = null;
		for (Page page : template.getPages()) {
			pages.add(page);
			page.setNeedRedraw(true);
		}
		
//		if (coverPage!=null){
//			pages.add(0, coverPage);
//		}
		
		book.setPages(pages);
		book.setSpine(template.getSpine());
		book.setProduct(product);
		project.setBook(book);
		project.setImages(images);
		
		if(project.getBook().getPages().get(0).getCaptions()!=null){
			if(project.getBook().getPages().get(0).getCaptions().size()>=2){
				SimpleDateFormat df = new SimpleDateFormat("yyyy.M.d");
				project.getBook().getPages().get(0).getCaptions().get(1).setText(df.format(new Date()));
			}
		}

		return putImageIntoBook(project,images,cacheDir);
	}
	
	private BookProject putImageIntoBook(BookProject project,Vector<File> images,String cacheDir){
		int pictureIndex =0;
		for (Page page : project.getBook().getPages()) {
			page.setComponentType();
			if (page.isHollow()|| page.getPictures() == null || page.getPictures().size()==0){
				continue;
			}
			else if (page.isJigsaw()) {
				generateJigsawPage(page,images);
			}
			else{
				for(PagePicture pagePicture:page.getPictures()){
					if (pagePicture.isClipart()){
						continue;
					}

					PictureHolder holder = pagePicture.getHolder();				
					ImageInfo imageInfo = new ImageInfo();
					File image = images.elementAt(pictureIndex);
					
					imageInfo.setPath(image.getPath());
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inJustDecodeBounds = true;
					BitmapFactory.decodeFile(image.getPath(), options);
					
					int degree = PictureUtil.readPictureDegree(image.getPath());
					float imageHeight =0;
					float imageWidth = 0;
					if (degree == 90 || degree == 270) {
						imageHeight = options.outWidth;
						imageWidth = options.outHeight;
					}else{
						imageHeight = options.outHeight;
						imageWidth = options.outWidth;
					}
					
					float heightRatio = holder.getHeight()/imageHeight;
					float widthRatio = holder.getWidth()/imageWidth;
//					if (holder.isAdaptToImageRatio()){
//						if (heightRatio > widthRatio ) {
//							float width = holder.getWidth();
//							float height = imageHeight * (float)(width/imageWidth);
//							imageInfo.setWidth(width);
//							imageInfo.setHeight(height);
//							imageInfo.setX(0);
//							imageInfo.setY(0);
//							holder.setY(holder.getY() + (holder.getHeight() -height)/2);
//							holder.setWidth(width);
//							holder.setHeight(height);
//						} else {
//							float height = holder.getHeight();
//							float width = imageWidth * (float)(height/imageHeight);
//							imageInfo.setWidth(width);
//							imageInfo.setHeight(height);
//							imageInfo.setX(0);
//							imageInfo.setY(0);
//							holder.setX(holder.getX() + (holder.getWidth() -width)/2);
//							holder.setWidth(width);
//							holder.setHeight(height);
//						}
//					}else{
						if (heightRatio > widthRatio ) {
							float height = holder.getHeight();
							float width = imageWidth * (float)(height/imageHeight);
							imageInfo.setWidth(width);
							imageInfo.setHeight(height);
							imageInfo.setX((holder.getWidth() - width)/2);
							imageInfo.setY(0);
						} else {
							float width = holder.getWidth();
							float height = imageHeight * width
									/ imageWidth;
							imageInfo.setWidth(width);
							imageInfo.setHeight(height);
							imageInfo.setX(0);
							imageInfo.setY((holder.getHeight()- height)/2);
						}
//						File savedFile = new File(cacheDir,imageInfo.getPath().substring(imageInfo.getPath().lastIndexOf("/")));
//						cropImageAndSaveToCache(imageInfo.getPath(), (int)holder.getHeight(),(int)holder.getWidth(),savedFile.getPath());
//						imageInfo.setPath(savedFile.getPath());
//						images.elementAt(pictureIndex);
//						images.remove(pictureIndex);
//						images.insertElementAt(savedFile, pictureIndex);
//					}
					
					pictureIndex++;
					if (pictureIndex== images.size()){
						pictureIndex =0;
					}
						
					pagePicture.setHolder(holder);
					
					pagePicture.setClipart(false);
					pagePicture.setImage(imageInfo);
				}
				
//				if (!page.isCover() && page.getCaptions()!=null && page.getCaptions().size()>0){
//					for(Caption caption:page.getCaptions()){
//						if (caption.getMarginTop()!=-1){
//							caption.setY( page.getPictures().get(0).getHolder().getY() + page.getPictures().get(0).getHolder().getHeight() + caption.getMarginTop());
//						}
//					}
//				}
			}
		}
		return project;
	}
	
//	private void cropImageAndSaveToCache(String fileName, int height,int weight,String cropedFileName){
//		try {
//
//			Bitmap image = PictureUtil.cropImage(fileName, height, weight);
//			// save file
//			File file = new File(cropedFileName);
//			FileOutputStream out = new FileOutputStream(file);
//			if (image.compress(Bitmap.CompressFormat.JPEG, 85, out)) {
//				out.flush();
//				out.close();
//			}
//
//			if (!image.isRecycled()) {
//				image.recycle();
//			}
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException ex) {
//			ex.printStackTrace();
//		}
//	}
	
	public void generateJigsawPage(BookProject project){
		for(Page page:project.getBook().getPages()){
			if (page.isJigsaw()){
				generateJigsawPage(page,project.getImages());
			}
		}
	}
	
	private void generateJigsawPage(Page page,Vector<File> images){
		HashSet<Integer> integerHashSet = new HashSet<Integer>();
		Random random = new Random();
		int randomPictures = page.getPictures().size();
		int picturesCnt = images.size();
		for (int i = 0; i < randomPictures; i++) {
			PagePicture pagePicture = page.getPictures().get(i);
			if (pagePicture.isClipart()){
				continue;
			}
			int randomInt = random.nextInt(picturesCnt);
			while (integerHashSet.contains(randomInt)) {
				randomInt = random.nextInt(picturesCnt);
			}
			integerHashSet.add(randomInt);
			File image = images.elementAt(randomInt);
			
			PictureHolder holder = pagePicture.getHolder();
			ImageInfo imageInfo = pagePicture.getImage();
			if (imageInfo ==null){
				imageInfo = new ImageInfo();
			}
			imageInfo.setPath(image.getPath());
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(image.getPath(), options);
			if (options.outHeight / options.outWidth > holder
					.getHeight() / holder.getWidth()) {
				float imageWidth = holder.getWidth();
				float imageHeight = options.outHeight * imageWidth
						/ options.outWidth;
				imageInfo.setWidth(imageWidth);
				imageInfo.setHeight(imageHeight);
				imageInfo.setX(0);
				imageInfo.setY((holder.getHeight() - imageHeight) / 2);
			} else {
				float imageHeight = holder.getHeight();
				float imageWidth = options.outWidth * imageHeight
						/ options.outHeight;
				imageInfo.setWidth(imageWidth);
				imageInfo.setHeight(imageHeight);
				imageInfo.setX((holder.getWidth() - imageWidth) / 2);
				imageInfo.setY(0);
			}
			pagePicture.setImage(imageInfo);
		}
	}

}
